import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:wuxu_flutter_lianxi/localization/default_localizations.dart';
import 'package:wuxu_flutter_lianxi/style/wx_style.dart';
import 'package:wuxu_flutter_lianxi/widget/pull/pull_scroll_physics.dart';
import 'package:wuxu_flutter_lianxi/widget/pull/refresh_sliver.dart' as IOS;

///
/// 下拉刷新控件
///

const double refreshHeight = 140;
const double refreshIndicatorExtent = 100;

typedef Callback = void Function();

class PullLoadWidget extends StatefulWidget {
  final ScrollController? scrollController;
  final PullLoadViewControl control;
  final Callback? refreshCallback;
  final Callback? loadMoreCallback;
  final IndexedWidgetBuilder itemBuilder;

  //GlobalKey 可在外部获取state
  final Key? refreshKey;

  PullLoadWidget(
    this.control,
    this.itemBuilder, {
    this.refreshKey,
    this.scrollController,
    this.loadMoreCallback,
    this.refreshCallback,
  });

  @override
  State<StatefulWidget> createState() {
    return PullLoadState();
  }
}

class PullLoadState extends State<PullLoadWidget> {
  ScrollController? _scrollController;

  late Function() _scrollListener;

  ///刷新
  @protected
  Future<void> handleRefresh() async {
    widget.refreshCallback ?? ();
    return;
  }

  /// 加载更多
  @protected
  Future<void> handleLoadMore() async {
    widget.loadMoreCallback ?? ();
    return;
  }

  Widget _buildHeader() {
    return Container(
      width: double.infinity,
      height: 50,
      color: Colors.yellow,
      child: Text("header"),
    );
  }

  Widget _buildEmpty() {
    return Container(
      height: double.infinity,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextButton(
              onPressed: () {},
              child: Image(
                image: AssetImage(WxIcons.empty),
                width: 70,
                height: 70,
              )),
          Container(
            child: Text(WxLocalizations.languageResString(context).appEmpty,
                style: WxConstant.normalText),
          )
        ],
      ),
    );
  }

  Widget _buildProgressIndicator() {
    Widget bottomWidget = (widget.control.needLoadMore)
        ? Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              SpinKitRotatingCircle(
                size: 20,
                color: Theme.of(context).primaryColor,
              ),
              Container(
                //分隔线的作用
                width: 5,
              ),
              Text(WxLocalizations.languageResString(context).loadMore,
                  style: const TextStyle(
                      color: Color(0xFF121917),
                      fontSize: 14.0,
                      fontWeight: FontWeight.bold))
            ],
          )
        //不需要加载，展示空widget
        : Container();

    return new Padding(
      padding: const EdgeInsets.all(20.0),
      child: new Center(
        child: bottomWidget,
      ),
    );
  }

  /// 算上 头、加载更多，实际总共的条目个数
  _getListCount() {
    if (widget.control.needHeader) {
      return (widget.control.dataList.isNotEmpty)
          //如果有头布局，那么当有数据时，总个数+2，否则当没有数据时+1 只算头布局的
          ? widget.control.dataList.length + 2
          : widget.control.dataList.length + 1;
    } else {
      return widget.control.dataList.length + 1;
    }
  }

  Widget _getItemWidget(int index) {
    //1.如果不需要头布局&&index 溢出&&数据不为空。 展示底部加载更多布局
    if (!widget.control.needHeader &&
        index == widget.control.dataList.length &&
        widget.control.dataList.isNotEmpty) {
      return _buildProgressIndicator();
    } else if (widget.control.needHeader &&
        widget.control.dataList.isNotEmpty &&
        index == _getListCount() - 1) {
      return _buildProgressIndicator();
    } else if (!widget.control.needHeader && widget.control.dataList.isEmpty) {
      return _buildEmpty();
    } else if (widget.control.needHeader) {
      return index == 0
          ? _buildHeader()
          : widget.itemBuilder(context, index - 1);
    } else {
      return widget.itemBuilder(context, index);
    }
  }

  @override
  void initState() {
    _scrollListener = () {
      //判断是否滑动到底部，触发加载更多
      if (_scrollController!.position.pixels ==
          _scrollController!.position.maxScrollExtent) {
        if (widget.control.needLoadMore) {
          handleLoadMore();
        }
      }
    };
    _scrollController = widget.scrollController ?? ScrollController();

    _scrollController?.addListener(_scrollListener);

    widget.control.addListener(() {
      setState(() {});
    });

    super.initState();
  }

  @override
  void dispose() {
    _scrollController?.removeListener(_scrollListener);
    super.dispose();
  }

  final GlobalKey<IOS.CupertinoSliverRefreshControlState> sliverRefreshKey =
  GlobalKey<IOS.CupertinoSliverRefreshControlState>();

  @override
  Widget build(BuildContext context) {
    return NotificationListener(
        onNotification: (notification) {
          if(notification is ScrollNotification){
            sliverRefreshKey.currentState!.notifyScrollNotification(notification);
          }
          return false;
        },
        child: CustomScrollView(
          //这里为什么要自定义PullScrollPhysics，因为ios与Android下拉效果是不同的，需要保持ui一致，同时处理滑动的一些情况
          physics: const PullScrollPhysics(
            parent: AlwaysScrollableScrollPhysics(),
            refreshHeight: refreshHeight
          ),
          controller: _scrollController,
          slivers: [
            //IOS风格刷新控件
            IOS.CupertinoSliverRefreshControl(
              key: sliverRefreshKey,
              refreshIndicatorExtent: refreshIndicatorExtent,
              refreshTriggerPullDistance: refreshHeight,
              onRefreshCallback: handleRefresh,

              builder: (context,
              refreshState,
              latestIndicatorBoxExtent,
              refreshTriggerPullDistance,
              refreshIndicatorExtent){
                return Container(
                  color: Colors.blue,
                  width: double.infinity,
                  height: 100,
                );
              },
            ),

            //主体列表
            SliverSafeArea(
                sliver: SliverList(
              delegate: SliverChildBuilderDelegate((context, index) {
                return _getItemWidget(index);
              }, childCount: _getListCount()),
            ))
          ],
        ));
  }
}

///
/// ChangeNotifier 用于响应式，结合Provider使用。数据变化通知ui刷新
///
class PullLoadViewControl extends ChangeNotifier {
  List _dataList = [];

  ///get是个函数
  List get dataList => _dataList;

  addList(List? value) {
    if (value != null) {
      _dataList.add(value);
      notifyListeners();
    }
  }

  set dataList(List? value) {
    _dataList.clear();
    if (value != null) {
      _dataList.addAll(value);
    }
    print("dataList:$_dataList");
    notifyListeners();
  }

  bool _needLoadMore = true;

  bool get needLoadMore => _needLoadMore;

  set needLoadMore(value) {
    _needLoadMore = value;
    notifyListeners();
  }

  bool _needHeader = true;

  bool get needHeader => _needHeader;

  set needHeader(value) {
    _needHeader = value;
    notifyListeners();
  }

  ///加载中
  bool isLoading = false;
}
